package com.tycmc.signelectroniccontracts.tools.htmlcommit;

import android.content.Context;
import android.graphics.Color;

import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.tycmc.signelectroniccontracts.R;
import com.tycmc.signelectroniccontracts.tools.adapter.recyclerview.GeneralRecyclerAdapter;
import com.tycmc.signelectroniccontracts.tools.adapter.recyclerview.GeneralViewHolder;
import com.tycmc.signelectroniccontracts.tools.adapter.recyclerview.RecycleViewDivider;
import com.tycmc.signelectroniccontracts.tools.adapter.recyclerview.RecyclerTool;
import com.tycmc.signelectroniccontracts.tools.htmlcommit.HtCommitEntity;
import com.tycmc.signelectroniccontracts.tools.htmlcommit.HtmlCommitCallBack;
import com.tycmc.signelectroniccontracts.tools.htmlcommit.HtmlType;
import com.tycmc.signelectroniccontracts.tools.htmlcommit.PopHtml;
import com.tycmc.signelectroniccontracts.tools.images.ImageSetting;
import com.tycmc.signelectroniccontracts.tools.other.MoneyValueFilter;
import com.tycmc.signelectroniccontracts.tools.other.NoChinseValueFilter;
import com.tycmc.signelectroniccontracts.tools.other.TextShow;
import com.tycmc.signelectroniccontracts.tools.times.DataTimer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HtCommitView extends LinearLayout {

    private Context context;
    private GeneralRecyclerAdapter<HtCommitEntity> adapter;
    private HtmlCommitCallBack commitCallBack;
    private Map<HtCommitEntity, HtCommitEntity> htMap = new HashMap<>();//保存所关联的对象的属性  key当前对象   value所关联的对象
    private Map<HtCommitEntity, View> htViewMap = new HashMap<>();//保存所关联的对象的对象属性  key当前对象   value view
    private Map<HtCommitEntity, List<HtCommitEntity>> htListMap = new HashMap<>();//保存所关联的对象的属性  key当前对象   value所被关联的对象集合
    private boolean isEdit;//是否可以进行编辑操作

    public HtCommitView(Context context) {
        this(context, null);
    }

    public HtCommitView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HtCommitView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        View inflate = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.layout_ht_commit, this, false);
        addView(inflate);
        initRecycleView();
        initView();
    }

    public void setCommitCallBack(HtmlCommitCallBack commitCallBack) {
        this.commitCallBack = commitCallBack;
    }

    private void initView() {
        findViewById(R.id.tv_ht_commit).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                commitCallBackData();
            }
        });
    }

    /**
     * 设置是否可以进行编辑
     *
     * @param isEdit true可以编辑 false 只能查看
     */
    public void setEdit(boolean isEdit) {
        this.isEdit = isEdit;
    }

    /**
     * 修改提交按钮
     * @param isEdit
     */
    public void setCommitVisible(boolean isEdit) {
        findViewById(R.id.tv_ht_commit).setVisibility(isEdit ? VISIBLE : GONE);
    }

    /**
     * 获取表单的内容数据
     */
    public void commitCallBackData() {
        List<HtCommitEntity> list = getAdapterList();
        Map map = getUpMap();
        if (map == null) return;
        if (commitCallBack != null) {
            commitCallBack.sucessCommit(map, list);
        }
    }

    @Nullable
    public Map getUpMap() {
        List<HtCommitEntity> list = getAdapterList();
        Map map = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            HtCommitEntity entity = list.get(i);
            if (entity != null) {
                if (entity.getIsneed().equals("1")) {
                    if (entity.getCss_style() == HtmlType.PICTERCHOSE) {
                        HtCommitEntity.PicterMapEntity mapEntity = entity.getPicterMapEntity();
                        List<String> picterList = mapEntity.getPicterList();
                        if (picterList.size() == 0) {
                            if (commitCallBack != null) {
                                commitCallBack.errorContent(entity.getNeedContent(), i);
                            }
                            return null;
                        }
                    } else if (TextUtils.isEmpty(entity.getShowcontent()) && isVisible(entity)) {
                        if (commitCallBack != null) {
                            commitCallBack.errorContent(entity.getNeedContent(), i);
                        }
                        return null;
                    }
                }
                if (!TextUtils.isEmpty(entity.getTagKey())) {
                    map.put(entity.getTagKey(), entity.getTagContent());
                }
                if (entity.getCss_style() == HtmlType.PICTERCHOSE) {
                    HtCommitEntity.PicterMapEntity mapEntity = entity.getPicterMapEntity();
                    List<String> picterList = mapEntity.getPicterList();
                    map.put(entity.getUpkey(), picterList);
                } else {
                    map.put(entity.getUpkey(), entity.getShowcontent());
                }
            }
        }
        return map;
    }

    public List<HtCommitEntity> getAdapterList() {
        return adapter.getmList();
    }

    private void initRecycleView() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
        recyclerView.setLayoutManager(RecyclerTool.setListView(context));
        recyclerView.addItemDecoration(new RecycleViewDivider(context, LinearLayoutManager.HORIZONTAL, 1, Color.TRANSPARENT));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new GeneralRecyclerAdapter<HtCommitEntity>(context) {
            @Override
            public int getViewType(HtCommitEntity entity) {
                return entity.getCss_style();
            }

            @Override
            public int getView(int type) {
                if (type == HtmlType.SIMPLETEXT) {//单行选择模式
                    return R.layout.chose_state_item;
                } else if (type ==HtmlType.SIMPLEEDIT) {//单行输入模式
                    return R.layout.input_state_item;
                } else if (type == HtmlType.MULTIEDIT) {
                    return R.layout.input_state_mutile_item;
                }  else if (type == HtmlType.SIMCHOSE) {
                    return R.layout.chose_state_item_check_box;
                }
                return 0;
            }

            @Override
            public void convert(final GeneralViewHolder helper, final HtCommitEntity item) {
                htViewMap.put(item, helper.getConvertView());
                helper.setGone(R.id.rl_back, !isVisible(item));
                helper.setText(R.id.tv_state, item.getShowkey());//显示提示
                helper.setTextNeed(R.id.tv_state, item.getIsneed().equals("1"));
                if (item.getCss_style() == HtmlType.SIMPLETEXT) {//单行选择模式
                    helper.setText(R.id.tv_chose, item.getShowcontent());
                    helper.setOnClickListener(R.id.tv_state, new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!isEdit) {
                                return;
                            }
                            if (item.getCss_id().equals(HtmlType.CHOSEDATA)) {//时间选择格式
                                HtCommitEntity.DataMapEntity entity = item.getDataMapEntity();
                                DataTimer.choseTime(context, new DataTimer.TimerCallBack() {
                                    @Override
                                    public void callBack(String time) {
                                        helper.setText(R.id.tv_chose, time);
                                        item.setShowcontent(time);
                                        if (commitCallBack != null) {
                                            commitCallBack.choseChange(item, adapter.getmList().indexOf(item));
                                        }
                                        refresh(item);
                                    }
                                }, item.getShowcontent(), entity.getStartTime(), entity.getEndTime(), entity.getIshour().equals("1"));

                            } else if (item.getCss_id().equals(HtmlType.CHOSETYPE)) {//选项卡模式
                                if (item.getChoselist().size() == 0) {
                                    if (commitCallBack != null) {
                                        commitCallBack.onclickOnItem(item, adapter.getmList().indexOf(item));
                                    }
                                } else {
                                    PopHtml popHtml = new PopHtml(context, item.getChoselist(), new PopHtml.OnItemListen() {
                                        @Override
                                        public void itemOnclick(AdapterView<?> parent, int position, View view) {
                                            if (parent.getAdapter().getItem(position) instanceof HtCommitEntity.ChoseDataEntity) {
                                                HtCommitEntity.ChoseDataEntity entity = (HtCommitEntity.ChoseDataEntity) parent.getAdapter().getItem(position);
                                                helper.setText(R.id.tv_chose, entity.getChosename());
                                                item.setShowcontent(entity.getChosename());
                                                item.setTagContent(entity.getChoseid());
                                                if (commitCallBack != null) {
                                                    commitCallBack.choseChange(item, adapter.getmList().indexOf(item));
                                                }
                                                refresh(item);
                                            }
                                        }
                                    });
                                    popHtml.show(v);
                                }

                            }

                        }
                    });

                } else if (item.getCss_style() == HtmlType.SIMPLEEDIT) {//单行输入模式
                    HtCommitEntity.InputMapEntity entity = item.getInputMapEntity();
                    helper.setTextHint(R.id.et_input, entity.getHintcontent());
                    helper.setText(R.id.et_input, item.getShowcontent());
//                    helper.setLines(R.id.et_input,entity.getLines() );
                    if (entity.getInputstytle().equals("number")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                    } else if (entity.getInputstytle().equals("numberdecimal")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                    } else if (entity.getInputstytle().equals("money")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new MoneyValueFilter()});
                    } else if (entity.getInputstytle().equals("alphabet")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                        helper.setKeyListener(R.id.et_input, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM");
                    } else if (entity.getInputstytle().equals("alphabetornumber")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength()), new NoChinseValueFilter()});
                        helper.setKeyListener(R.id.et_input, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789");
                    } else {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                    }

                    helper.addTextChangedListener(R.id.et_input, new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            item.setShowcontent(s.toString().trim());
                            refresh(item);
                        }
                    });
                    helper.setEnabled(R.id.et_input, isEdit);
                } else if (item.getCss_style() == HtmlType.MULTIEDIT) {
                    final HtCommitEntity.InputMapEntity entity = item.getInputMapEntity();
                    helper.setTextHint(R.id.et_input, entity.getHintcontent());

                    helper.setText(R.id.et_input, item.getShowcontent());
                    if (entity.getInputstytle().equals("number")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                    } else if (entity.getInputstytle().equals("numberdecimal")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                    } else if (entity.getInputstytle().equals("money")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength()), new MoneyValueFilter()});
                    } else if (entity.getInputstytle().equals("alphabet")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                    } else if (entity.getInputstytle().equals("alphabetornumber")) {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength()), new NoChinseValueFilter()});
                    } else {
                        helper.setInputType(R.id.et_input, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                        helper.setFilters(R.id.et_input, new InputFilter[]{new InputFilter.LengthFilter(entity.getInputlength())});
                    }
                    helper.setLines(R.id.et_input, entity.getLines());
                    helper.setText(R.id.tv_word_num, item.getShowcontent().trim().length() + "/" + entity.getInputlength());
                    helper.addTextChangedListener(R.id.et_input, new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            item.setShowcontent(s.toString().trim());
                            helper.setText(R.id.tv_word_num, s.toString().trim().length() + "/" + entity.getInputlength());
                            refresh(item);
                        }
                    });
                } else if (item.getCss_style() == HtmlType.SIMCHOSE) {
                    helper.setChecked(R.id.cb_chose, item.getShowcontent().equals("1"));
                    helper.setOnClickListener(R.id.cb_chose, new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CheckBox box = (CheckBox) v;
                            if (box.isChecked()) {
                                item.setShowcontent("1");
                            } else {
                                item.setShowcontent("0");
                            }
                        }
                    });
                }
            }
        };
        recyclerView.setAdapter(adapter);
    }

    public boolean isVisible(HtCommitEntity item) {
        if (htMap.get(item) != null) {
            HtCommitEntity entity = htMap.get(item);
            boolean isShow = (item.getRelationsname().equals("等于") && entity.getShowcontent().equals(item.getRelation_value()))
                    || (item.getRelationsname().equals("不等于") && !entity.getShowcontent().equals(item.getRelation_value()))
                    || (item.getRelationsname().equals("大于")
                    && (DataTimer.getLongTime(entity.getShowcontent(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm")
                    > DataTimer.getLongTime(TextShow.isEmpty(item.getRelation_value()) ? DataTimer.getNowString(entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm") : item.getRelation_value(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm")))
                    || (item.getRelationsname().equals("小于") && (DataTimer.getLongTime(entity.getShowcontent(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm")
                    < DataTimer.getLongTime(TextShow.isEmpty(item.getRelation_value()) ? DataTimer.getNowString(entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm") : item.getRelation_value(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm")))
                    || (item.getRelationsname().equals("小于等于") && (DataTimer.getLongTime(entity.getShowcontent(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm")
                    <= DataTimer.getLongTime(TextShow.isEmpty(item.getRelation_value()) ? DataTimer.getNowString(entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm") : item.getRelation_value(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm")))
                    || (item.getRelationsname().equals("小于等于")) && (DataTimer.getLongTime(entity.getShowcontent(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm")
                    >= DataTimer.getLongTime(TextShow.isEmpty(item.getRelation_value()) ? DataTimer.getNowString(entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm") : item.getRelation_value(), entity.getDataMapEntity().getIshour().equals("0") ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm"));
            // 是否是关联属性  是否是对应的关联字段
            return (item.getRelation().equals("1") && entity.getUpkey().equals(item.getRelation_name()) && isShow && isVisible(entity)) || item.getRelation().equals("0");
        }
        return true;
    }

    public void refresh(HtCommitEntity item) {
        if (htListMap.get(item) != null) {
            List<HtCommitEntity> htCommitEntities = htListMap.get(item);
            for (int i = 0; i < htCommitEntities.size(); i++) {
                HtCommitEntity htCommitEntity = htCommitEntities.get(i);
                View view = htViewMap.get(htCommitEntity);
                boolean visible = isVisible(htCommitEntity);
                if (view != null) {
                    if (view.findViewById(R.id.rl_back) != null) {
                        view.findViewById(R.id.rl_back).setVisibility(visible ? VISIBLE : GONE);
                    }
                    if (!visible) {
                        if (view.findViewById(R.id.tv_chose) != null) {
                            ((TextView) view.findViewById(R.id.tv_chose)).setText("");
                        }
                        if (view.findViewById(R.id.et_input) != null) {
                            ((TextView) view.findViewById(R.id.et_input)).setText("");
                        }
                    }
                }
            }
        }
    }

    /**
     * 初始化数据来源
     *
     * @param list
     */
    public void initData(List<HtCommitEntity> list) {
        initData(list, null, true);
    }

    /**
     * 初始化数据来源，保存默认数据
     *
     * @param list
     * @param updata
     */
    public void initData(List<HtCommitEntity> list, Map<String, Object> updata) {
        initData(list, updata, true);
    }

    /**
     * 初始化数据来源
     *
     * @param list
     * @param updata
     * @param isEdit 是否可以修改
     */
    public void initData(List<HtCommitEntity> list, Map<String, Object> updata, boolean isEdit) {
        setEdit(isEdit);
        htMap.clear();
        htViewMap.clear();
        htListMap.clear();
        //若只能查看 则要进行赋值操作
        if (updata != null) {
            for (int i = 0; i < list.size(); i++) {
                HtCommitEntity entity = list.get(i);
                if (entity.getCss_style() == HtmlType.PICTERCHOSE) {
                    entity.getPicterMapEntity().setPicterList((List<String>) updata.get(entity.getUpkey()));
                } else {
                    entity.setShowcontent(TextShow.valueOf(updata.get(entity.getUpkey())));
                }


            }
        }

        adapter.replaceAll(list);
        List<HtCommitEntity> listRelation = new ArrayList<>();//保存当前存在关联的对象
        List<HtCommitEntity> relationList = new ArrayList<>();//所属关联属性
        List<HtCommitEntity> adaList = getAdapterList();
        for (int i = 0; i < adaList.size(); i++) {
            HtCommitEntity entity = adaList.get(i);
            if (entity.getRelation().equals("1")) {
                listRelation.add(entity);
            }
        }
        //将所有需要关联的 和 目标对象 关联在一起
        for (int i = 0; i < listRelation.size(); i++) {
            HtCommitEntity entity = listRelation.get(i);
            for (int j = 0; j < adaList.size(); j++) {
                HtCommitEntity adaEntity = adaList.get(j);
                if (entity.getRelation_name().equals(adaEntity.getUpkey())) {
                    htMap.put(entity, adaEntity);
                    relationList.add(adaEntity);
                    break;
                }
            }
        }
        for (int i = 0; i < relationList.size(); i++) {
            HtCommitEntity entity = relationList.get(i);
            List<HtCommitEntity> list1 = new ArrayList<>();
            for (int j = 0; j < adaList.size(); j++) {
                HtCommitEntity adaEntity = adaList.get(j);
                if (entity.getUpkey().equals(adaEntity.getRelation_name())) {
                    list1.add(adaEntity);
                }
            }

            htListMap.put(entity, list1);
        }
    }

    public void addData(HtCommitEntity entity, int positon) {
        adapter.add(entity, positon);
    }

    public void addAll(List<HtCommitEntity> list, int position) {
        adapter.addAll(list, position);
    }

    //更新
    public void notifyItemChanged(int position) {
        adapter.notifyItemChanged(position);
    }

}
